package com.jike.mahjong.common.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.model.RequestMethod;
import org.codehaus.jackson.map.util.JSONPObject;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理后台参数传递工具类
 * Created by star on 2016/10/8.
 */
public class HttpUtil {

    /**
     * 获取url传参
     *
     * @param request
     * @param key
     * @return
     */
    public static String getHttpParameter(HttpServletRequest request, String key) {
        String str = request.getParameter(key);
        return str;
    }

    /**
     * 添加session变量
     *
     * @param request
     * @param key
     * @param value
     */
    public static void setSessionAttribute(HttpServletRequest request, String key, Object value) {
        try {
            request.getSession().setAttribute(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取session变量
     *
     * @param request
     * @param key
     * @return
     */
    public static Object getSessionAttribute(HttpServletRequest request, String key) {
        Object obj = request.getSession().getAttribute(key);
        return obj;
    }

    /**
     * 清除session数据
     */
    public static void clear(HttpServletRequest request, String key) {
        request.getSession().removeAttribute(key);
    }


    public static String PostWithJson(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "text/html"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.write(params);
            out.flush();
            out.close();
            // 读取响应
            InputStream is = connection.getInputStream();
            String br="";
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuffer sb = new StringBuffer();

            while ((br = reader.readLine()) != null)
            {
                sb.append(br).append("\n");
            }
            return sb.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

    /**
     * 根据request获取参数列表
     *
     * @param params
     *            request中的参数列表
     * @return 转换为map<String, String>
     */
    public  static Map<String, Object> paramsToMap(Map<String, String[]> params) {
        // 返回的map对象
        Map<String, Object> paramMap = new HashMap<String, Object>();
        // 遍历request种的参数列表
        for (String key : params.keySet()) {
            String[] values = params.get(key);
            String value = values[0];
            paramMap.put(key, value);
        }
        return paramMap;
    }


    public static void main(String [] args){




        String params="{'cmd':'unLockPlayer','args':['1094']}";

       /* Map<String,Object> paras=new HashMap<String,Object>();
        paras.put("cmd","lockPlayer");
        List<String> arr=new ArrayList<>();
        arr.add("1");
        arr.add("2");
        paras.put("args",arr);

        Gson gson=new Gson();
        String result=gson.toJson(paras);*/



     /*   Map<String,Object>  resultMap=gson.fromJson(result,HashMap.class);*/


        JsonParser jsonParser=new JsonParser();

        String result =PostWithJson(Constants.BACK_URL,params);
        JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
        System.out.println(result);
        System.out.println(jsonObject.get("msg"));

    }



}
